package com.cskaoyan.config;

import com.cskaoyan.bean.MallAdmin;
import com.cskaoyan.bean.MallAdminExample;
import com.cskaoyan.mapper.MallAdminMapper;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @author stone
 * @date 2022/04/09 10:54
 */
@Component
public class MarketRealm extends AuthorizingRealm {

    @Autowired
    MallAdminMapper mapper;

    //获得认证信息
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        //subject执行login → Authenticator的doAuthenticate方法 → 使用到realm提供的doGetAuthenticationInfo
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        //根据用户名查询：当前用户在系统中的真实密码 Credentials
        //从subject.login传进来的
        String username = token.getUsername();

        MallAdminExample example = new MallAdminExample();
        example.createCriteria().andUsernameEqualTo(username);
        List<MallAdmin> mallAdmins = mapper.selectByExample(example);
        if (mallAdmins == null || mallAdmins.size() == 0) {
            return null;
        }
        MallAdmin mallAdmin = mallAdmins.get(0);
        //来源于数据库的真实密码
        String password = mallAdmin.getPassword();

        //1.Shiro管理的用户信息，你需要Shiro管理什么样的用户信息，就提供什么用户信息
        //2.真实密码 → 根据token中提供的用户名查出来的 → 这个值在认证器中会和token中的password做比较
        //3.realm的名称 → 可以作为不同realm的区分，但其实没太大用处
        return new SimpleAuthenticationInfo(mallAdmin, password, this.getName());
    }

    //获得授权信息
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        //授权方法中可以拿到用户信息
        MallAdmin primaryPrincipal = (MallAdmin) principalCollection.getPrimaryPrincipal();
        return null;
    }
}
